<template>
  <div class="warehouse-page">
    <!-- 页面标题 -->
    <div class="page-title">
      <h2>仓库管理</h2>
      <p>Warehouse Management</p>
    </div>

    <!-- 仓库列表区域 -->
    <div class="warehouse-list">
      <!-- 新建仓库卡片 -->
      <div class="warehouse-card add-card" @click="handleAddWarehouse" hover>
        <div class="add-icon">
          <el-icon size="30" color="#23c6c8"> <Plus /> </el-icon>
        </div>
        <div class="add-text">新建仓库</div>
        <div class="add-subtext">Add New Warehouse</div>
      </div>

      <!-- 仓库卡片（循环渲染） -->
      <div class="warehouse-card" v-for="(item, index) in warehouseList" :key="index" hover>
        <!-- 卡片内容区域（点击打开库存弹窗） -->
        <div class="card-content" @click="openStockDialog(item)">
          <!-- 仓库标题栏 -->
          <div class="card-header">
            <div class="warehouse-name">
              <el-icon> <UserFilled /> </el-icon>
              {{ item.name }}
            </div>
            <!-- 下拉菜单区域（不触发库存弹窗） -->
            <div class="dropdown-container">
              <el-dropdown size="mini" trigger="click">
                <el-icon> <More /> </el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleEditWarehouse(item)">编辑</el-dropdown-item>
                    <el-dropdown-item @click="handleDeleteWarehouse(index)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <!-- 仓库金额 -->
          <div class="warehouse-amount">¥ {{ item.amount }}</div>

          <!-- 产品数量进度条 -->
          <div class="product-count">{{ item.productCount }}件产品</div>
          <div class="progress-container">
            <div 
              class="progress-bar" 
              :style="{ width: (item.productCount / 500 * 100) + '%' }"
            ></div>
          </div>

          <!-- 品牌范围 -->
          <div class="brand-range">
            品牌范围: {{ item.brandRange }}
          </div>

          <!-- 仓库地址 -->
          <div class="warehouse-address">
            <i class="el-icon-map-marker" style="margin-right: 4px;"></i>
            {{ item.address }}
          </div>

          <!-- 负责人信息 -->
          <div class="manager-info">
            <i class="el-icon-user" style="margin-right: 4px;"></i>
            <span>{{ item.manager }}</span>
            <i class="el-icon-mobile-phone" style="margin: 0 8px 0 12px;"></i>
            <span>{{ item.phone }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 1. 库存查询弹窗（点击仓库卡片打开） -->
    <el-dialog 
      title="查询库存" 
      v-model="stockDialogVisible" 
      width="90%" 
 
      destroy-on-close
    >
      <!-- 搜索区域 -->
      <div class="stock-search-area" style="margin-bottom: 20px; display: flex; align-items: center; gap: 15px;">
        <el-select v-model="stockSearch.brand" placeholder="请选择品牌" style="width: 120px;">
          <el-option label="丝芙兰" value="丝芙兰" />
          <el-option label="蓝妮尔" value="蓝妮尔" />
        </el-select>
        <el-select v-model="stockSearch.category" placeholder="产品分类" style="width: 120px;">
          <el-option label="单品" value="单品" />
          <el-option label="套盒" value="套盒" />
        </el-select>
        <el-input 
          v-model="stockSearch.keyword" 
          placeholder="请输入关键字" 
          style="width: 200px;"
          suffix-icon="el-icon-search"
          @keyup.enter="handleStockSearch"
        />
        <el-button type="primary" icon="search" @click="handleStockSearch" style="background-color: #10b981; border-color: #10b981;">
          搜索
        </el-button>
      </div>

      <!-- 库存表格 -->
      <el-table 
        :data="filteredStockList" 
        border 
        stripe 
       
      >
        <el-table-column prop="productNo" label="产品编号" align="center" />
        <el-table-column prop="productName" label="产品名称" align="center" />
        <el-table-column prop="brand" label="归属品牌" align="center" />
        <el-table-column prop="spec" label="规格" align="center" />
        <el-table-column prop="type" label="类型" align="center" />
        <el-table-column prop="retailPrice" label="零售价" align="center" />
        <el-table-column prop="discountRule" label="折扣" align="center" />
        <el-table-column prop="discountPrice" label="折扣价" align="center" />
        <el-table-column prop="specialPrice" label="特价" align="center" />
        <el-table-column prop="seckillPrice" label="秒杀价" align="center" />
        <el-table-column prop="warehouse" label="仓库" align="center" />
        <el-table-column prop="stock" label="库存" align="center" />
        <el-table-column prop="inDate" label="入库日期" align="center" />
        <el-table-column prop="validDays" label="有效期" align="center" />
        <el-table-column label="操作" align="center" width="300">
          <template #default>
            <el-button type="success" >编辑</el-button>
            <el-button type="danger" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 合计行 -->
      <div class="stock-total" style="margin-top: 10px; padding: 10px; border: 1px solid #ebeef5; border-top: none; display: flex; align-items: center; gap: 20px;">
        <span>合计</span>
        <span style="margin-left: 50px;">-</span>
        <span>-</span>
        <span>-</span>
        <span>-</span>
        <span>-</span>
        <span>-</span>
        <span>¥{{ totalDiscountPrice }}</span>
        <span>-</span>
        <span>¥{{ totalSpecialPrice }}</span>
        <span>¥{{ totalSeckillPrice }}</span>
        <span>-</span>
        <span>{{ totalStock }}</span>
        <span>-</span>
        <span>-</span>
        <span>-</span>
      </div>

      <!-- 分页区域 -->
      <div class="stock-pagination" style="margin-top: 20px; display: flex; align-items: center; gap: 15px;">
        <span>共 {{ filteredStockList.length }} 条 共 {{ stockTotalPages }} 页</span>
        <el-pagination
          @current-change="handleStockPageChange"
          :current-page="stockCurrentPage"
          :page-size="10"
          layout="prev, pager, next"
          :total="filteredStockList.length"
          background
          size="small"
        />
        <span>10条/页</span>
        <span>跳至</span>
        <el-input 
          v-model="stockJumpPage" 
          type="number" 
          style="width: 50px; margin: 0 5px;"
          size="small"
          min="1"
        />页
        <el-button 
          type="primary" 
         
          @click="handleStockJumpPage"
          style="background-color: #10b981; border-color: #10b981;"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 2. 新建/编辑仓库弹窗 -->
    <el-dialog 
      :title="isEditMode ? '编辑仓库' : '新建仓库'" 
      v-model="dialogVisible" 
      width="600px" 
      top="20vh"
      destroy-on-close
    >
      <!-- 基本信息区域 -->
      <div class="dialog-section">
        <div class="section-title">基本信息</div>
        <div class="form-row">
          <div class="form-item">
            <label>仓库名称：</label>
            <el-input v-model="warehouseForm.name" placeholder="请输入仓库名称" />
          </div>
          <div class="form-item">
            <label>仓库地址：</label>
            <el-input v-model="warehouseForm.address" placeholder="请输入仓库地址" />
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label>电话：</label>
            <el-input v-model="warehouseForm.phone" placeholder="请输入联系电话" />
          </div>
          <div class="form-item">
            <label>负责人：</label>
            <el-input v-model="warehouseForm.manager" placeholder="请输入负责人" />
          </div>
        </div>
      </div>

      <!-- 仓库品牌区域 -->
      <div class="dialog-section">
        <div class="section-title">仓库品牌</div>
        <div class="brand-checkboxes">
          <el-checkbox v-model="warehouseForm.brands" label="蓝泥尔" />
          <el-checkbox v-model="warehouseForm.brands" label="臻药" />
          <el-checkbox v-model="warehouseForm.brands" label="贝亦美" />
          <el-checkbox v-model="warehouseForm.brands" label="OD" />
          <el-checkbox v-model="warehouseForm.brands" label="和悦肽" />
        </div>
      </div>

      <!-- 保存按钮 -->
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="isEditMode ? handleUpdateWarehouse() : handleSaveWarehouse()"
          class="save-btn"
        >
          保存内容
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, UserFilled, More } from '@element-plus/icons-vue';

// 仓库列表数据
const warehouseList = ref([
  {
    name: '1号仓库',
    amount: '109800',
    productCount: 354,
    brandRange: '蓝妮尔/臻药/贝亦美/OD和悦肽',
    manager: '李三燕',
    phone: '13235461389',
    address: '上海市浦东新区张江高科技园区',
    brands: ['蓝妮尔', '臻药', '贝亦美', 'OD', '和悦肽']
  },
  {
    name: '2号仓库',
    amount: '128197',
    productCount: 361,
    brandRange: '蓝妮尔/臻药/贝亦美/OD和悦肽',
    manager: '李三燕',
    phone: '13235461389',
    address: '北京市海淀区中关村大街',
    brands: ['蓝妮尔', '臻药', '贝亦美', 'OD', '和悦肽']
  },
  {
    name: '3号仓库',
    amount: '123374',
    productCount: 372,
    brandRange: '蓝妮尔/臻药/贝亦美/OD和悦肽',
    manager: '李三燕',
    phone: '13235461389',
    address: '广州市天河区珠江新城',
    brands: ['蓝妮尔', '臻药', '贝亦美', 'OD', '和悦肽']
  }
]);

// 库存数据
const stockList = ref([
  {
    productNo: '4545',
    productName: '丝芙兰',
    brand: '丝芙兰精华眼霜',
    spec: '50g',
    type: '单品',
    retailPrice: '¥111.62',
    discountRule: '单品1.2 套盒2.3',
    discountPrice: '¥123.98',
    specialPrice: '¥123.98',
    seckillPrice: '¥111.62',
    warehouse: '1号',
    stock: 65426,
    inDate: '2022.8.29',
    validDays: '355天'
  },
  {
    productNo: '4545',
    productName: '丝芙兰',
    brand: '丝芙兰精华眼霜',
    spec: '50g',
    type: '套盒',
    retailPrice: '¥111.62',
    discountRule: '单品1.2 套盒2.3',
    discountPrice: '¥123.98',
    specialPrice: '¥123.98',
    seckillPrice: '¥111.62',
    warehouse: '1号',
    stock: 65426,
    inDate: '2022.8.29',
    validDays: '355天'
  },
  {
    productNo: '4545',
    productName: '丝芙兰',
    brand: '丝芙兰精华眼霜',
    spec: '50g',
    type: '单品',
    retailPrice: '¥111.62',
    discountRule: '单品1.2 套盒2.3',
    discountPrice: '¥123.98',
    specialPrice: '¥123.98',
    seckillPrice: '¥111.62',
    warehouse: '1号',
    stock: 65426,
    inDate: '2022.8.29',
    validDays: '355天'
  }
]);

// 状态管理
const state = reactive({
  // 仓库弹窗
  dialogVisible: false,
  isEditMode: false,
  currentIndex: -1,
  warehouseForm: {
    name: '默认仓库',
    address: '',
    phone: '',
    manager: '',
    brands: []
  },
  // 库存弹窗
  stockDialogVisible: false,
  currentWarehouse: {},
  stockSearch: {
    brand: '',
    category: '',
    keyword: ''
  },
  stockCurrentPage: 1,
  stockJumpPage: ''
});

const { 
  dialogVisible, isEditMode, currentIndex, warehouseForm,
  stockDialogVisible, currentWarehouse, stockSearch,
  stockCurrentPage, stockJumpPage
} = toRefs(state);

// 筛选后的库存列表
const filteredStockList = computed(() => {
  return stockList.value.filter(item => {
    // 品牌筛选
    if (stockSearch.value.brand && item.brand !== stockSearch.value.brand) return false;
    // 分类筛选
    if (stockSearch.value.category && item.type !== stockSearch.value.category) return false;
    // 关键字筛选
    if (stockSearch.value.keyword) {
      const keyword = stockSearch.value.keyword.trim().toLowerCase();
      return item.productName.toLowerCase().includes(keyword) 
        || item.productNo.includes(keyword)
        || item.brand.toLowerCase().includes(keyword);
    }
    return true;
  });
});

// 库存分页总页数
const stockTotalPages = computed(() => {
  return Math.ceil(filteredStockList.value.length / 10) || 1;
});

// 库存合计数据
const totalDiscountPrice = computed(() => {
  return filteredStockList.value.reduce((sum, item) => {
    return sum + Number(item.discountPrice.replace('¥', ''));
  }, 0).toFixed(2);
});
const totalSpecialPrice = computed(() => {
  return filteredStockList.value.reduce((sum, item) => {
    return sum + Number(item.specialPrice.replace('¥', ''));
  }, 0).toFixed(2);
});
const totalSeckillPrice = computed(() => {
  return filteredStockList.value.reduce((sum, item) => {
    return sum + Number(item.seckillPrice.replace('¥', ''));
  }, 0).toFixed(2);
});
const totalStock = computed(() => {
  return filteredStockList.value.reduce((sum, item) => sum + item.stock, 0);
});

// 打开库存弹窗（点击仓库卡片触发）
const openStockDialog = (warehouse) => {
  currentWarehouse.value = warehouse;
  // 重置搜索条件
  stockSearch.value = { brand: '', category: '', keyword: '' };
  stockCurrentPage.value = 1;
  stockDialogVisible.value = true;
};

// 库存搜索
const handleStockSearch = () => {
  stockCurrentPage.value = 1;
};

// 库存分页切换
const handleStockPageChange = (val) => {
  stockCurrentPage.value = val;
};

// 库存页码跳转
const handleStockJumpPage = () => {
  const page = Number(stockJumpPage.value);
  if (page && page >= 1 && page <= stockTotalPages.value) {
    stockCurrentPage.value = page;
  } else {
    ElMessage.error(`请输入1-${stockTotalPages.value}之间的页码`);
  }
};

// 新建仓库
const handleAddWarehouse = () => {
  warehouseForm.value = {
    name: '默认仓库',
    address: '',
    phone: '',
    manager: '',
    brands: []
  };
  isEditMode.value = false;
  dialogVisible.value = true;
};

// 编辑仓库
const handleEditWarehouse = (item) => {
  warehouseForm.value = { ...item };
  isEditMode.value = true;
  currentIndex.value = warehouseList.value.findIndex(w => w.name === item.name);
  dialogVisible.value = true;
};

// 保存新仓库
const handleSaveWarehouse = () => {
  if (!warehouseForm.value.name.trim()) {
    ElMessage.error('请输入仓库名称');
    return;
  }
  if (warehouseForm.value.brands.length === 0) {
    ElMessage.error('请至少选择一个仓库品牌');
    return;
  }

  const brandRange = warehouseForm.value.brands.join('/');
  warehouseList.value.push({
    ...warehouseForm.value,
    amount: '0',
    productCount: 0,
    brandRange
  });

  ElMessage.success('仓库创建成功');
  dialogVisible.value = false;
};

// 更新仓库
const handleUpdateWarehouse = () => {
  if (!warehouseForm.value.name.trim()) {
    ElMessage.error('请输入仓库名称');
    return;
  }
  if (warehouseForm.value.brands.length === 0) {
    ElMessage.error('请至少选择一个仓库品牌');
    return;
  }

  const brandRange = warehouseForm.value.brands.join('/');
  warehouseList.value[currentIndex.value] = {
    ...warehouseList.value[currentIndex.value],
    ...warehouseForm.value,
    brandRange
  };

  ElMessage.success('仓库更新成功');
  dialogVisible.value = false;
};

// 删除仓库
const handleDeleteWarehouse = (index) => {
  ElMessageBox.confirm(
    `确定要删除【${warehouseList.value[index].name}】吗？`,
    '删除确认',
    { type: 'warning' }
  ).then(() => {
    warehouseList.value.splice(index, 1);
    ElMessage.success('仓库已删除');
  });
};
</script>

<style scoped>
.warehouse-page {
  padding: 30px;
  background-color: #f9fafb;
  min-height: 100vh;
}

/* 页面标题样式 */
.page-title {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-title h2 {
  font-size: 22px;
  color: #1f2937;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.page-title p {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.warehouse-list {
  display: flex;
  gap: 155px;
  flex-wrap: wrap;
}

/* 卡片基础样式 - 250×350px */
.warehouse-card {
  width: 250px;
  height: 350px;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  padding: 22px;
  box-sizing: border-box;
  background-color: #fff;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

/* 卡片内容区域（可点击打开弹窗） */
.card-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  cursor: pointer;
}

/* 下拉菜单容器（不触发弹窗） */
.dropdown-container {
  cursor: default;
}

/* 卡片悬停效果 */
.warehouse-card[hover]:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.02);
  border-color: #d1d5db;
}

/* 新建仓库卡片 */
.add-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: #fafafa;
  border: 1px dashed #d1d5db;
}

.add-card:hover {
  background-color: #f3f4f6;
  border-color: #10b981;
}

.add-icon {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
  transition: all 0.3s ease;
}

.add-card:hover .add-icon {
  background-color: #dcfce7;
}

.add-icon i {
  font-size: 24px;
  color: #10b981;
}

.add-text {
  font-size: 16px;
  color: #374151;
  margin-bottom: 6px;
  font-weight: 500;
}

.add-subtext {
  font-size: 12px;
  color: #9ca3af;
  letter-spacing: 0.5px;
}

/* 仓库卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 15px;
  color: #374151;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f3f4f6;
}

.warehouse-name {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.warehouse-name i {
  color: #6b7280;
  font-size: 16px;
}

/* 金额样式 */
.warehouse-amount {
  font-size: 30px;
  font-weight: 600;
  color: #111827;
  margin: 10px 0;
  line-height: 1;
  position: relative;
  padding-left: 2px;
  text-align: center;
}

/* .warehouse-amount::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -6px;
  width: 30px;
  height: 3px;
  background-color: #10b981;
  border-radius: 2px;
} */

/* 产品数量与进度条 */
.product-count {
  font-size: 15px;
  color: #9ca3af;
  margin-bottom: 6px;
  margin-top: 15px;
  text-align: center;
}

.progress-container {
  height: 10px;
  background: #f3f4f6;
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 20px;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.05);
}

.progress-bar {
  height: 100%;
  background: #23c6c8;
  border-radius: 3px;
  transition: width 1s ease-in-out;
}

/* 品牌范围 */
.brand-range {
  font-size: 13px;
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  padding: 8px 0;
  border-top: 1px dashed #f3f4f6;
  border-bottom: 1px dashed #f3f4f6;
}

/* 仓库地址 */
.warehouse-address {
  font-size: 13px;
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.warehouse-address i {
  color: #ef4444;
}

/* 负责人信息 */
.manager-info {
  font-size: 13px;
  color: #9ca3af;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding-top: 10px;
  border-top: 1px solid #f3f4f6;
}

/* 弹窗样式 */
.el-dialog__header {
  border-bottom: 1px solid #f3f4f6;
  padding-bottom: 15px;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.dialog-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
  border-left: 3px solid #10b981;
  padding-left: 8px;
  font-weight: 500;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 25px;
  margin-bottom: 18px;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 12px;
  width: calc(50% - 12px);
}

.form-item label {
  width: 80px;
  text-align: right;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.form-item .el-input {
  width: 200px;
  transition: border-color 0.2s;
}

.form-item .el-input:focus-within {
  border-color: #10b981;
}

.brand-checkboxes {
  display: flex;
  align-items: center;
  gap: 20px;
  padding-left: 92px;
  flex-wrap: wrap;
}

.save-btn {
  background-color: #10b981;
  border-color: #10b981;
  transition: all 0.2s;
}

.save-btn:hover {
  background-color: #059669;
  border-color: #059669;
}

/* 库存表格合计行样式 */
.stock-total {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .warehouse-page {
    padding: 15px;
  }
  
  .form-item {
    width: 100%;
  }
  
  .brand-checkboxes {
    padding-left: 0;
    justify-content: flex-start;
  }
  
  .warehouse-list {
    gap: 15px;
    justify-content: center;
  }
}
</style>